package cn.wolfcode.luowowo2.search.service.impl;

import cn.wolfcode.luowowo2.search.query.SearchQueryObject;
import cn.wolfcode.luowowo2.search.repository.IDestinationTemplateRepository;
import cn.wolfcode.luowowo2.search.repository.IStrategyTemplateRepository;
import cn.wolfcode.luowowo2.search.service.IDestinationSearchService;
import cn.wolfcode.luowowo2.search.service.IStrategySearchService;
import cn.wolfcode.luowowo2.search.template.StrategyTemplate;
import cn.wolfcode.luowowo2.search.vo.StatisVO;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregation;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.util.*;

/**
 * Created by Albert on 2019/7/15.
 */
@Service
public class StrategySearchServiceImpl implements IStrategySearchService{
    @Autowired
    private IStrategyTemplateRepository dao;

    @Autowired
    private ElasticsearchTemplate template;

    @Autowired
    private TransportClient client;

    @Override
    public void createIndex() {
        template.createIndex(StrategyTemplate.class);
        template.putMapping(StrategyTemplate.class);
        
    }

    @Override
    public void save(StrategyTemplate template) {
        dao.save(template);
    }

    @Override
    public List<Map<String, Object>> queryThemeCommends() {
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
        TermsValuesSourceBuilder idSource = new TermsValuesSourceBuilder("id");
        idSource.field("themeId"); //分组字段
        idSource.missingBucket(true); //忽略不满足条件的bucket

        TermsValuesSourceBuilder nameSource = new TermsValuesSourceBuilder("name");
        nameSource.field("themeName");
        nameSource.missingBucket(true);

        sources.add(idSource);
        sources.add(nameSource);
        //设置分组民称与分组字段集合
        CompositeAggregationBuilder builder = new CompositeAggregationBuilder("themeGroup", sources);

        //设置索引
        SearchRequest request = new SearchRequest(StrategyTemplate.INDEX_NAME);
        //设置类
        request.types(StrategyTemplate.TYPE_NAME);

        request.source(
                new SearchSourceBuilder()
                .aggregation(builder)
                .size(0)
        );

        //发起请求
        SearchResponse response = this.client.search(request).actionGet();
        Aggregations aggregations = response.getAggregations();
        //聚合查询分组对象
        CompositeAggregation compositeAggregation = aggregations.get("themeGroup");

        //结果封装
        List<? extends CompositeAggregation.Bucket> buckets = compositeAggregation.getBuckets();
        List<StatisVO> themesVos = new ArrayList<>();

        for (CompositeAggregation.Bucket bucket : buckets) {
            StatisVO vo = new StatisVO();
            Map<String, Object> key = bucket.getKey();
            vo.setId(Long.valueOf(key.get("id").toString()));
            vo.setName(key.get("name").toString());
            vo.setCount(bucket.getDocCount());
            themesVos.add(vo);
        }
        //排序
        Collections.sort(themesVos, new Comparator<StatisVO>() {
            @Override
            public int compare(StatisVO o1, StatisVO o2) {
                return o2.getCount().compareTo(o1.getCount());
            }
        });

        //取前10个
        if (themesVos.size()>10) {
            themesVos = themesVos.subList(0,10);
        }
        //外层
        List<Map<String,Object>> data = new ArrayList<>();

        //内层,主题和目的地集合
        Map<String,Object> map;
        for (StatisVO vo : themesVos) {
            List<StatisVO> dests = queryDestByThemeId(vo.getId());
            map = new HashMap<>();
            map.put("themes",vo);
            map.put("dests",dests);
            data.add(map);
        }

        return data;
    }

    @Override
    public List<StatisVO> querythemeCondition(int conditionType) {
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();
        TermsValuesSourceBuilder idSource = new TermsValuesSourceBuilder("id");
        idSource.missingBucket(true);

        TermsValuesSourceBuilder nameSource = new TermsValuesSourceBuilder("name");
        nameSource.missingBucket(true);

        //查询过滤条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (conditionType == SearchQueryObject.CONDITION_TYPE_ABROAD) {
            idSource.field("countryId");
            nameSource.field("countryName");
            //国家的id不能为1
            boolQuery.mustNot(QueryBuilders.termQuery("countryId",1));

        } else if (conditionType == SearchQueryObject.CONDITION_TYPE_INNER) {
            idSource.field("provinceId");
            nameSource.field("provinceName");
            boolQuery.must(QueryBuilders.termQuery("countryId",1));
        } else if (conditionType == SearchQueryObject.CONDITION_TYPE_THEME) {
            idSource.field("themeId");
            nameSource.field("themeName");
        }

        sources.add(idSource);
        sources.add(nameSource);
        //设置分组民称与分组字段集合
        CompositeAggregationBuilder builder = new CompositeAggregationBuilder("themeGroup", sources);

        //设置索引
        SearchRequest request = new SearchRequest(StrategyTemplate.INDEX_NAME);
        //设置类
        request.types(StrategyTemplate.TYPE_NAME);

        request.source(
                new SearchSourceBuilder()
                        .aggregation(builder)
                        .query(boolQuery)
                        .size(0)
        );

        //发起请求
        SearchResponse response = this.client.search(request).actionGet();
        Aggregations aggregations = response.getAggregations();
        //聚合查询分组对象
        CompositeAggregation compositeAggregation = aggregations.get("themeGroup");

        //封装结果
        List<? extends CompositeAggregation.Bucket> buckets = compositeAggregation.getBuckets();
        List<StatisVO> vos = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : buckets) {
            StatisVO vo = new StatisVO();
            Map<String, Object> key = bucket.getKey();
            vo.setId(Long.valueOf(key.get("id").toString()));
            vo.setName(key.get("name").toString());
            vo.setCount(bucket.getDocCount());
            vos.add(vo);
        }

        return vos;
    }

    @Override
    public Page<StrategyTemplate> query(SearchQueryObject qo) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String idFiled = "";
        String nameField = "";
        if (qo.getType()== SearchQueryObject.CONDITION_TYPE_ABROAD) {
            boolQuery.must(QueryBuilders.termQuery("countryId",qo.getTypeValue()));
        } else if (qo.getType() == SearchQueryObject.CONDITION_TYPE_INNER) {
            boolQuery.must(QueryBuilders.termQuery("provinceId", qo.getTypeValue()));
        } else if (qo.getType() == SearchQueryObject.CONDITION_TYPE_THEME){
            boolQuery.must(QueryBuilders.termQuery("themeId",qo.getTypeValue()));
        }

        Page<StrategyTemplate> page = dao.search(boolQuery,qo.getPageable());

        return page;
    }

    @Override
    public Page<StrategyTemplate> queryStrategy(SearchQueryObject qo) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (qo.getDestId()!=null) {
            boolQuery.must(QueryBuilders.termQuery("destId",qo.getDestId()));
        }
        return dao.search(boolQuery,qo.getPageableWithOutSort());
    }

    private List<StatisVO> queryDestByThemeId(Long themeId) {
        List<StatisVO> list = new ArrayList<>();
        Iterable<StrategyTemplate> iterable = dao.search(QueryBuilders.termQuery("themeId", themeId));
        iterable.forEach(s->{
            StatisVO vo = new StatisVO();
            vo.setId(s.getDestId());
            vo.setName(s.getDestName());
            list.add(vo);
        });
        return list;
    }
}
